package cn.iocoder.yudao.module.member.growth.service.core;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.business.basic.service.impl.AbstractService;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.module.api.member.growth.enums.MemberGrowthBizTypeEnum;
import cn.iocoder.yudao.module.member.assets.dal.dataobject.MemberDigitalAssetsDO;
import cn.iocoder.yudao.module.member.assets.service.AppMemberDigitalAssetsService;
import cn.iocoder.yudao.module.member.growth.dao.GrowthRecordMapper;
import cn.iocoder.yudao.module.member.growth.pojo.po.GrowthRecord;
import cn.iocoder.yudao.module.member.growth.pojo.vo.GrowthRecordVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 服务
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/05/08
 */
@Service
public class CoreGrowthRecordService extends AbstractService<GrowthRecord, GrowthRecordVO> {
    @Resource
    private GrowthRecordMapper growthRecordMapper;

    @Resource
    private AppMemberDigitalAssetsService memberDigitalAssetsService;

    @Override
    public GrowthRecordMapper getInjectedMapper() {
        return growthRecordMapper;
    }

    /**
     * 创建用户贡献值记录
     *
     * @param userId  用户ID
     * @param growth   变动贡献值，负数表示减少
     * @param bizType 业务类型
     * @param bizId   业务编号
     */
    @Transactional(rollbackFor = Exception.class)
    public void createGrowthRecord(Long userId, String inviteeName, LocalDateTime inviteeTime, Integer growth, MemberGrowthBizTypeEnum bizType, String bizId) {
        // 1. 校验用户贡献值
        MemberDigitalAssetsDO digitalAssets = memberDigitalAssetsService.getOrCreate(userId);
        int userGrowth = NumberUtil.nullToZero(digitalAssets.getGrowth());
        int totalGrowth = userGrowth + growth; // 用户变动后的贡献值
        Assertions.isTrue(totalGrowth >= 0, "贡献值余额不足");
        // 2. 更新用户贡献值
        memberDigitalAssetsService.changeGrowth(userId, growth);
        // 3. 增加贡献值记录
        GrowthRecord record = new GrowthRecord();
        record.setUserId(userId);
        record.setBizId(bizId);
        record.setBizType(bizType.getValue());
        record.setTitle(StrUtil.format(bizType.getName(), inviteeName));
        record.setDescription(StrUtil.format(bizType.getSummary(), inviteeName, Math.abs(growth)));
        record.setGrowth(growth);
        record.setTotalGrowth(totalGrowth);
        record.setInviteeTime(inviteeTime);
        getInjectedMapper().insert(record);
    }

}
